/*
 * @Author: yuta
 * @Date: 2021-09-17 14:43:14
 * @LastEditTime: 2021-12-23 15:18:20
 * @LastEditors: yuta
 */
import React from 'react'
import {TouchableOpacity, View, ViewStyle} from 'react-native'
import Theme from '@path/config/theme'
import {px2dp} from '@path/config/system'
import {ThemeText} from '@path/components/ThemeComponents'
import {createMaterialTopTabNavigator, MaterialTopTabBarProps} from '@react-navigation/material-top-tabs'
import ShadowWrap, {ShadowWrapProps} from '@path/components/ShadowWrap'

export interface TopTabNavProps {
  tabs: tabProps[]
  children?: (routeProps) => JSX.Element
  initialRouteName?: string
  messageNum?: number
  containerStyle?: ViewStyle
  type?: Type
  isEnableShadow?: boolean
  shadowConfig?: ShadowWrapProps
}

type Type = 'bottom' | 'around'

interface tabProps {
  title: string
  params?: any
  component?: JSX.Element
}

const TopTab = createMaterialTopTabNavigator()

const TopTabNav = (props: TopTabNavProps) => {
  const {
    tabs,
    children,
    initialRouteName,
    messageNum,
    containerStyle,
    type = 'bottom',
    isEnableShadow,
    shadowConfig,
  } = props

  const WrapShadow = (wrapProps: any) => {
    return isEnableShadow ? (
      <ShadowWrap containerViewStyle={{zIndex: 100}} {...shadowConfig}>
        {wrapProps?.children}
      </ShadowWrap>
    ) : (
      wrapProps.children
    )
  }

  const _renderTabBar = ({state, descriptors, navigation}: MaterialTopTabBarProps) => {
    return (
      <WrapShadow>
        <View
          style={{
            width: '100%',
            height: px2dp(41),
            flexDirection: 'row',
            alignItems: 'center',
            justifyContent: 'space-between',
            paddingHorizontal: px2dp(18),
            ...containerStyle,
          }}>
          <View
            style={{
              flex: 1,
              flexDirection: 'row',
              alignItems: 'center',
              justifyContent: 'space-around',
            }}>
            {state.routes.map((route, index) => {
              const {options} = descriptors[route.key]
              const label =
                options.tabBarLabel !== undefined
                  ? options.tabBarLabel
                  : options.title !== undefined
                  ? options.title
                  : route.name

              const isFocused = state.index === index

              const onPress = () => {
                const event = navigation.emit({
                  type: 'tabPress',
                  target: route.key,
                  canPreventDefault: true,
                })

                if (!isFocused && !event.defaultPrevented) {
                  // The `merge: true` option makes sure that the params inside the tab screen are preserved
                  navigation.navigate({name: route.name, merge: true, params: {}})
                }
              }

              return (
                <TouchableOpacity
                  activeOpacity={0.8}
                  style={{alignItems: 'center'}}
                  onPress={() => {
                    onPress()
                  }}>
                  <View
                    style={{
                      flexDirection: 'row',
                      alignItems: 'center',
                      ...(type === 'around'
                        ? isFocused
                          ? {
                              backgroundColor: Theme.getThemeColor('theme'),
                              borderRadius: 12,
                              height: px2dp(24),
                              minWidth: px2dp(64),
                              justifyContent: 'center',
                              alignItems: 'center',
                            }
                          : {}
                        : {}),
                    }}>
                    {type === 'bottom' ? (
                      <ThemeText
                        style={{
                          fontSize: 15,
                          color: isFocused ? Theme.getThemeColor('theme') : Theme.getThemeColor('text_minor'),
                          fontWeight: '500',
                          textAlign: 'center',
                        }}>
                        {label}
                      </ThemeText>
                    ) : null}

                    {type === 'around' ? (
                      <ThemeText
                        style={{
                          fontSize: 13,
                          color: isFocused ? '#fff' : Theme.getThemeColor('text_main'),
                          fontWeight: '500',
                          textAlign: 'center',
                        }}>
                        {label}
                      </ThemeText>
                    ) : null}
                  </View>

                  {type === 'bottom' ? (
                    <View
                      style={{
                        alignSelf: 'center',
                        width: px2dp(17),
                        height: px2dp(3),
                        marginTop: px2dp(10),
                        backgroundColor: Theme.getThemeColor('theme'),
                        opacity: isFocused ? 1 : 0,
                      }}
                    />
                  ) : null}
                </TouchableOpacity>
              )
            })}
          </View>
        </View>
      </WrapShadow>
    )
  }

  return (
    <TopTab.Navigator
      initialRouteName={initialRouteName}
      sceneContainerStyle={{
        backgroundColor: 'transparent',
      }}
      screenOptions={{lazy: true}}
      tabBar={_renderTabBar}>
      {tabs.map((item, index: number) => {
        return children ? ( // 两种形式，一种是tab内容一致的，可直接传children；一种是内容有差异的，传各自的页面给component
          <TopTab.Screen key={index} name={item.title} initialParams={item.params}>
            {children}
          </TopTab.Screen>
        ) : item.component ? (
          <TopTab.Screen key={index} name={item.title} initialParams={item.params} component={item.component} />
        ) : null
      })}
    </TopTab.Navigator>
  )
}

export default TopTabNav
